package Test;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author shy_black
 * @date 2019/4/30 16:27
 * @Description:
 */
class SemaphoreTask implements  Runnable {
    private Semaphore semaphore;
    public SemaphoreTask(Semaphore semaphore) {
        this.semaphore = semaphore;
    }
    @Override
    public void run() {
        //尝试获取资源
        try {
            semaphore.acquire();
            System.out.println(Thread.currentThread().getName() + "正在使用设备");
            TimeUnit.SECONDS.sleep(2);
            System.out.println(Thread.currentThread().getName() + "使用设备完毕");
            semaphore.release();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
public class 信号量 {
    public static void main(String[] args) {
        //5台机器
        //10个工人
        Semaphore semaphore = new Semaphore(5);
        for(int i = 1;i <= 10;i++) {
            new Thread(new SemaphoreTask(semaphore),"work"+i).start();
        }
    }
}
